<template>
  <view>
    <view @click="toPay()">
      <slot></slot>
    </view>
	  <uni-pay ref="pay" @success="paySuccess" @cancel="cancel" @fail="fail" :toSuccessPage="false" :debug="true"></uni-pay>
  </view>
</template>
<script lang="ts" setup>
import { ref, defineProps } from 'vue';

const vk = uni.vk;

const cardStyle = `
  border: none;
  background: #fff7ec;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
`

const createOrder = async () => {
	let res;
	try {
		res = await vk.callFunction({
			url: 'client/order/kh/add',
			title: '请求中...',
			data: {
				orderType: 'goods',
				notityType: 'goods',
				extendData: {
					goods_id: props.goodsInfo._id
				}
			}
		});
	} catch(err){
		return Promise.reject('订单创建失败')
	}
	if (!res) return Promise.reject('订单创建失败');

	return res;
}

let pay = ref(null);
const toPay = async () => {
	let orderResult: { code: number; data: any; };
	try {
		orderResult = await createOrder();
	} catch(err){
		console.log(err);
		vk.toast('订单创建失败');
	}
	const data = vk.pubfn.string2Number(orderResult.data)

	if (orderResult && orderResult.code === 0) {
		pay.value.open(data);
		close();
	} else {
		throw new Error('支付失败！')
	}
}
const emit = defineEmits(["update:modelValue", "paysuccess"]);
const paySuccess = () => {
	console.log('paysuccess');
  emit('paysuccess')
}
const cancel = () => {
	vk.toast('取消支付');
}
const fail = () => {
	vk.toast('支付失败');
}

const props = defineProps({
  modelValue: {
    type: String,
    default: ref(false)
  },
  goodsInfo: {
    type: Object,
    default: () => {}
  }
})

const close = () => {
  emit('update:modelValue', false);
}

</script>
<style scoped lang="less">
.dialog-footer button:first-child {
  margin-right: 10px;
}
.vip-header {
  margin-top: 40rpx;
  color: #834f1d;
  .title {
    font-size: 54rpx;
    font-weight: bold;
  }

  .desc {
    font-size: 24rpx;
  }
}
.vip-list {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  border-radius: 18px;
  margin-bottom: 40rpx;
}
.vip-item {
  margin: 10rpx 5px;
  min-width: 500rpx;

  &-main {
    display: flex;
    align-items: flex-end;
  }

  &-desc {
    font-size: 34rpx;
    line-height: 34rpx;
    color: #6d6257;
    letter-spacing: 2px;
  }

  &-price {
    font-size: 110rpx;
    line-height: 60rpx;
    color: #f94532;
  }

  &-origin-price {
    font-size: 34rpx;
    line-height: 34rpx;
    color: #98928c;
    text-decoration: line-through;
    margin: 20rpx 0;
  }
}

.pay-btn {
  width: 300rpx;
  color: #804a19;
}
</style>
